package com.youxin.chat.pay.service.manager;

import com.alibaba.fastjson.JSONObject;
import com.youxin.base.BaseResultCode;
import com.youxin.chat.pay.context.CommonOrderContext;
import com.youxin.chat.pay.context.TransactionContext;
import com.youxin.chat.pay.enums.RedStatusEnum;
import com.youxin.chat.pay.mapper.*;
import com.youxin.chat.pay.model.*;
import com.youxin.chat.user.dto.UserInfoDto;
import com.youxin.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * description: RedPackManager <br>
 * date: 2020/2/29 15:08 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class RedPackManager {

    private static final Logger logger = LoggerFactory.getLogger(RedPackManager.class);
    @Resource
    private UserWalletMapper userWalletMapper;

    @Resource
    private RedSendMapper redSendMapper;

    @Resource
    private TransactionDetailMapper transactionDetailMapper;

    @Resource
    private CommonOrderMapper commonOrderMapper;

    @Resource
    private RedReceiveMapper redReceiveMapper;

    @Transactional
    public String saveSendInfo(RedSend redSend) {
        int count = userWalletMapper.doSendRedPack(redSend.getRedAmount(), redSend.getUserNo());
        if (count < 1) {
            logger.error("用户余额不足,data={}", JSONObject.toJSONString(redSend));
            throw new SystemException(BaseResultCode.BALANCE_NOT_ENOUGH, "用户余额不足");
        }
        UserWallet userWallet = userWalletMapper.selectById(redSend.getUserNo());
        redSendMapper.insert(redSend);
        TransactionDetail detail = TransactionContext.buildTransactionDetail(redSend,userWallet.getAgentNo());
        transactionDetailMapper.insert(detail);
        CommonOrder commonOrder = CommonOrderContext.buildCommonOrder(redSend,userWallet.getAgentNo());
        commonOrderMapper.insert(commonOrder);
        return redSend.getId();
    }

    @Transactional
    public void saveReceiveInfo(RedSend redSend, UserInfoDto userInfo, BigDecimal amount, Integer finish, String ip) {

        RedReceive redReceive = new RedReceive();
        redReceive.setAmount(amount);
        redReceive.setUserNo(userInfo.getUserNo());
        redReceive.setNickName(userInfo.getNickName());
        redReceive.setAvatar(userInfo.getAvatar());
        redReceive.setRedId(redSend.getId());
        redReceive.setReceiveTime(LocalDateTime.now());
        redReceive.setCreateTime(LocalDateTime.now());
        redReceive.setUpdateTime(LocalDateTime.now());
        redReceiveMapper.insert(redReceive);
        userWalletMapper.doReceiveRedPack(amount, userInfo.getUserNo());
        int count = redSendMapper.doReceive(amount, finish, redSend.getId());
        if (count < 1) {
            logger.error("保存数据异常,data={}", JSONObject.toJSONString(redSend));
            throw new SystemException(BaseResultCode.INTERNAL_ERROR, "系统内部异常");
        }
        UserWallet userWallet = userWalletMapper.selectById(userInfo.getUserNo());
        TransactionDetail transactionDetail = TransactionContext.buildTransactionDetail(redSend.getId(), userInfo.getUserNo(), amount,userWallet.getAgentNo());
        transactionDetailMapper.insert(transactionDetail);
        CommonOrder commonOrder = CommonOrderContext.buildCommonOrder(redReceive, ip,userWallet.getAgentNo());
        commonOrderMapper.insert(commonOrder);
    }

    @Transactional
    public int doExpire(RedSend redSend, String refundOrderNo) {
        int count = redSendMapper.doExpire(RedStatusEnum.EXPIRE.getStatus(), refundOrderNo, redSend.getId());
        if (count < 1) {
            logger.error("过期红包已处理,id={}", redSend.getId());
            throw new SystemException(BaseResultCode.COMMON_FAIL,"过期红包处理失败");
        }
        BigDecimal leftAmount = redSend.getRedAmount().subtract(redSend.getReceiveAmount());
        if (leftAmount.compareTo(new BigDecimal(0)) > 0) {
            count = userWalletMapper.doExpireRedPack(leftAmount, redSend.getUserNo());
            if (count < 1) {
                logger.error("过期红包处理失败,余额更新失败,id={},userNo={}", redSend.getId(), redSend.getUserNo());
                throw new SystemException(BaseResultCode.COMMON_FAIL,"过期红包处理失败");
            }
            UserWallet userWallet = userWalletMapper.selectById(redSend.getUserNo());
            TransactionDetail transactionDetail = TransactionContext.buildExpireDetail(redSend.getId(), redSend.getUserNo(), leftAmount,userWallet.getAgentNo());
            count = transactionDetailMapper.insert(transactionDetail);
            if (count < 1) {
                logger.error("过期红包处理失败,添加结算信息失败,id={},userNo={}", redSend.getId());
                throw new SystemException(BaseResultCode.COMMON_FAIL,"过期红包处理失败");
            }
        }
        count = commonOrderMapper.insert(CommonOrderContext.buildExpireCommonOrder(redSend, refundOrderNo, leftAmount));
        if (count < 1) {
            logger.error("过期红包处理失败,添加通用信息失败,id={},userNo={}", redSend.getId());
            throw new SystemException(BaseResultCode.COMMON_FAIL,"过期红包处理失败");
        }
        return count;
    }
}
